package vip.xiaomoli.validator.validators;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import vip.xiaomoli.validator.constraints.Exists;
import vip.xiaomoli.validator.model.Api;
import vip.xiaomoli.validator.util.Checker;

public class ExistsValidator implements ConstraintValidator<Exists, Object> {

    private Api api;

    private String fieldName;

    @Override
    public void initialize(Exists ann) {
        api = new Api(ann.apiClass(), ann.methodName());
        fieldName = ann.fieldName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        boolean result = Checker.isExists(api, value);
        if (!result) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(
                    fieldName + "[" + value + "]" + "不存在"
            ).addConstraintViolation();
        }
        return result;
    }

}
